import axios from 'axios';
import * as vscode from 'vscode';
import { MCPServer, MCPServerListResponse } from './models';

export class ApiService {
  private context: vscode.ExtensionContext;

  constructor(context: vscode.ExtensionContext) {
    this.context = context;
  }
  
  // 获取API基础URL
  private getApiBaseUrl(): string {
    const config = vscode.workspace.getConfiguration('mcphub');
    return config.get('apiUrl') || 'http://mcp.clouddragon.huawei.com/api';
  }
  
  // 获取Web基础URL
  private getWebBaseUrl(): string {
    const config = vscode.workspace.getConfiguration('mcphub');
    return config.get('webUrl') || 'http://mcp.clouddragon.huawei.com';
  }

  async getMCPServerList(page: number = 1, pageSize: number = 20, query: string = ''): Promise<MCPServerListResponse> {
    try {
      const apiBaseUrl = this.getApiBaseUrl();
      console.log(`获取MCP Server列表: ${apiBaseUrl}/servers`);
      
      const response = await axios.get(`${apiBaseUrl}/servers`, {
        params: {
          page,
          page_size: pageSize,
          search: query
        }
      });

      // 根据Django REST Framework的分页响应格式处理数据
      return {
        servers: response.data.results.map((server: any) => this.transformServerData(server)),
        total: response.data.count,
        page: page,
        pageSize: pageSize
      };
    } catch (error) {
      console.error('获取MCP Server 列表失败:', error);
      vscode.window.showErrorMessage(`无法获取MCP Server列表: ${error instanceof Error ? error.message : String(error)}`);
      return { servers: [], total: 0, page: 1, pageSize: 20 };
    }
  }

  async getMCPServerDetail(id: string): Promise<MCPServer> {
    if (!id) {
      throw new Error('Server ID不能为空');
    }
    
    try {
      const apiBaseUrl = this.getApiBaseUrl();
      console.log(`获取MCP Server详情: ${apiBaseUrl}/servers/${id}`);
      
      const response = await axios.get(`${apiBaseUrl}/servers/${id}`);
      return this.transformServerData(response.data);
    } catch (error) {
      console.error(`获取MCP Server ${id} 详情失败:`, error);
      throw new Error(`获取MCP Server ${id} 详情失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }

  async getMCPServerReadme(id: string): Promise<string> {
    if (!id) {
      return '无效的Server ID';
    }
    
    try {
      const apiBaseUrl = this.getApiBaseUrl();
      console.log(`获取MCP Server README: ${apiBaseUrl}/servers/${id}/readme`);
      
      const response = await axios.get(`${apiBaseUrl}/servers/${id}/readme`);
      return response.data.content || '';
    } catch (error) {
      console.error(`获取MCP Server ${id} README失败:`, error);
      return `无法加载README: ${error instanceof Error ? error.message : String(error)}`;
    }
  }

  async getInstalledMCPServers(): Promise<MCPServer[]> {
    // 从存储中获取已安装的MCP Server 列表
    const installedServers = this.context.globalState.get<string[]>('installedServers', []);
    
    if (installedServers.length === 0) {
      return [];
    }
    
    // 获取详细信息
    const serverDetails: MCPServer[] = [];
    for (const serverId of installedServers) {
      try {
        const server = await this.getMCPServerDetail(serverId);
        server.installed = true;
        serverDetails.push(server);
      } catch (error) {
        console.error(`获取已安装MCP Server ${serverId} 详情失败:`, error);
      }
    }
    
    return serverDetails;
  }

  async installMCPServer(server: MCPServer): Promise<boolean> {
    if (!server || !server.id) {
      throw new Error('无效的MCP Server');
    }
    
    try {
      // 保存到已安装列表
      const installedServers = this.context.globalState.get<string[]>('installedServers', []);
      if (!installedServers.includes(server.id)) {
        installedServers.push(server.id);
        await this.context.globalState.update('installedServers', installedServers);
      }
      
      return true;
    } catch (error) {
      console.error(`安装MCP Server ${server.id} 失败:`, error);
      throw new Error(`安装MCP Server ${server.id} 失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }

  async openServerInBrowser(server: MCPServer): Promise<void> {
    if (!server || !server.id) {
      throw new Error('无效的MCP Server');
    }
    
    try {
      // 从配置获取Web地址
      const webBaseUrl = this.getWebBaseUrl();
      const url = `${webBaseUrl}/servers/${server.id}`;
      
      // 直接使用vscode打开浏览器链接
      const success = await vscode.env.openExternal(vscode.Uri.parse(url));
      if (!success) {
        throw new Error('无法在浏览器中打开链接');
      }
    } catch (error) {
      console.error(`在浏览器中打开Server ${server.id} 失败:`, error);
      vscode.window.showErrorMessage(`无法在浏览器中打开MCP Server: ${error instanceof Error ? error.message : String(error)}`);
    }
  }

  // 转换后端数据到我们需要的格式
  private transformServerData(data: any): MCPServer {
    return {
      id: data.id,
      name: data.name || '未命名Server',
      description: data.description || data.description_cn || '',
      version: data.version || '1.0.0',
      author: data.provider || '',
      github: data.github || '',
      isInternal: data.is_internal || false,
      authType: data.auth_method,
      language: data.dev_language,
      configJsonList: data.configs?.map((config: any) => ({
        name: config.name,
        json: JSON.stringify(config.content, null, 2)
      })) || [],
      installCommands: data.install_commands?.map((cmd: any) => ({
        name: cmd.name,
        command: cmd.command
      })) || [],
      installPrompt: data.install_prompt || '确定要安装此MCP Server吗？',
      installed: false
    };
  }
} 